<template>
    <div class="rich-text-editor">
      <Editor 
        ref="editorRef"
        v-model="content" 
        :min-height="minHeight"
        :height="height"
        :read-only="readOnly"
        @update:modelValue="handleChange"
      />
      <div v-if="showToolbar" class="editor-toolbar">
        <el-button type="primary" size="small" @click="insertVariable">插入变量</el-button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, watch } from 'vue'
  import Editor from '@/components/Editor/index.vue'
  
  const props = defineProps({
    modelValue: {
      type: String,
      default: ''
    },
    minHeight: {
      type: Number,
      default: 300
    },
    height: {
      type: Number,
      default: null
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    showToolbar: {
      type: Boolean,
      default: false
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'insert-variable'])
  
  const content = ref(props.modelValue || '')
  const editorRef = ref(null)
  
  // Watch for changes in props.modelValue
  watch(() => props.modelValue, (newVal) => {
    if (newVal !== content.value) {
      content.value = newVal
    }
  }, { immediate: true })
  
  // Handle content changes
  function handleChange(val) {
    content.value = val
    emit('update:modelValue', val)
  }
  
  // Trigger insert variable event
  function insertVariable() {
    emit('insert-variable')
  }
  
  // 添加插入内容方法  function insertContent(content) {    if (!content) return        // 获取编辑器实例    const quill = editorRef.value.getQuill()        if (!quill) {      console.error('Quill实例不存在');      return;    }        // 获取当前选中范围    const range = quill.getSelection(true)        // 在当前光标位置插入内容    if (range) {      // 检查内容是否为HTML格式      if (content.startsWith('<') && content.endsWith('>')) {        // 插入HTML内容        quill.clipboard.dangerouslyPasteHTML(range.index, content);      } else {        // 插入纯文本        quill.insertText(range.index, content);      }      // 调整光标到插入内容之后      quill.setSelection(range.index + 1, 0);    } else {      // 如果没有选中范围，则在末尾插入      const lastIndex = quill.getLength() - 1;      if (content.startsWith('<') && content.endsWith('>')) {        quill.clipboard.dangerouslyPasteHTML(lastIndex, content);      } else {        quill.insertText(lastIndex, content);      }      quill.setSelection(lastIndex + 1, 0);    }  }
  
  // 暴露方法给父组件defineExpose({  insertContent,  getQuill: () => {    if (editorRef.value) {      return editorRef.value.getQuill();    }    return null;  }})
  </script>
  
  <style scoped>
  .rich-text-editor {
    position: relative;
  }
  
  .editor-toolbar {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }
  </style>